from . import db
from datetime import datetime
import json

class WorkOrder(db.Model):
    __tablename__ = 'work_orders'
    
    id = db.Column(db.Integer, primary_key=True)
    order_number = db.Column(db.String(50), unique=True, nullable=False)
    title = db.Column(db.String(200), nullable=True)  # 设为可选字段
    description = db.Column(db.Text)
    type = db.Column(db.String(50), default='maintenance')  # maintenance, cleaning, safety, other
    priority = db.Column(db.String(20), default='medium')  # low, medium, high, urgent
    status = db.Column(db.String(20), default='pending')  # pending, assigned, in_progress, completed, cancelled
    location = db.Column(db.String(200))  # 位置信息
    notes = db.Column(db.Text)  # 备注信息
    
    # 时间字段
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    scheduled_start = db.Column(db.DateTime)
    scheduled_end = db.Column(db.DateTime)
    actual_start = db.Column(db.DateTime)
    actual_end = db.Column(db.DateTime)
    
    # 关联关系
    creator_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    assignee_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    group_id = db.Column(db.Integer, db.ForeignKey('groups.id'))
    area_id = db.Column(db.Integer, db.ForeignKey('areas.id'))  # 区域字段
    
    creator = db.relationship('User', foreign_keys=[creator_id], backref='created_orders')
    assignee = db.relationship('User', foreign_keys=[assignee_id], backref='assigned_orders')
    group = db.relationship('Group', backref='work_orders')
    area = db.relationship('Area', backref='work_orders')
    
    # 自定义字段值
    field_values = db.relationship('WorkOrderFieldValue', backref='work_order', cascade='all, delete-orphan')
    
    def to_dict(self, include_custom_fields=True):
        """转换为字典"""
        result = {
            'id': self.id,
            'order_number': self.order_number,
            'title': self.title,
            'description': self.description,
            'type': self.type,
            'priority': self.priority,
            'status': self.status,
            'location': self.location,
            'notes': self.notes,
            'creator_id': self.creator_id,
            'creator_name': self.creator.name if self.creator else None,
            'assignee_id': self.assignee_id,
            'assignee_name': self.assignee.name if self.assignee else None,
            'group_id': self.group_id,
            'group_name': self.group.name if self.group else None,
            'area_id': self.area_id,
            'area_name': self.area.name if self.area else None,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
            'scheduled_start': self.scheduled_start.isoformat() if self.scheduled_start else None,
            'scheduled_end': self.scheduled_end.isoformat() if self.scheduled_end else None,
            'actual_start': self.actual_start.isoformat() if self.actual_start else None,
            'actual_end': self.actual_end.isoformat() if self.actual_end else None
        }
        
        if include_custom_fields:
            result['custom_fields'] = {}
            for field_value in self.field_values:
                value = field_value.value
                
                # 处理多选字段的值，将JSON字符串转换为数组
                if field_value.field.field_type == 'checkbox' and value:
                    try:
                        if isinstance(value, str) and (value.startswith('[') or value.startswith('"[')):
                            value = json.loads(value)
                    except (json.JSONDecodeError, ValueError):
                        # 如果解析失败，保持原值
                        pass
                
                result['custom_fields'][field_value.field.name] = {
                    'value': value,
                    'field_type': field_value.field.field_type,
                    'label': field_value.field.label
                }
        
        return result
    
    def __repr__(self):
        return f'<WorkOrder {self.order_number}>'


class WorkOrderField(db.Model):
    """工单字段定义（包括基础字段和自定义字段）"""
    __tablename__ = 'work_order_fields'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False, unique=True)  # 字段名称（用于程序）
    label = db.Column(db.String(100), nullable=False)  # 字段标签（用于显示）
    field_type = db.Column(db.String(20), nullable=False)  # text, number, date, select, textarea, checkbox
    options = db.Column(db.Text)  # 选项（JSON格式，用于select类型）
    is_required = db.Column(db.Boolean, default=False)
    default_value = db.Column(db.Text)
    placeholder = db.Column(db.String(200))  # 提示文字
    sort_order = db.Column(db.Integer, default=0)
    is_active = db.Column(db.Boolean, default=True)
    field_category = db.Column(db.String(20), default='custom')  # basic=基础字段, custom=自定义字段
    is_visible = db.Column(db.Boolean, default=True)  # 是否显示（用于基础字段的显示控制）
    system_required = db.Column(db.Boolean, default=False)  # 系统必需字段
    description = db.Column(db.Text)  # 字段描述
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'label': self.label,
            'field_type': self.field_type,
            'options': json.loads(self.options) if self.options else None,
            'is_required': self.is_required,
            'default_value': self.default_value,
            'placeholder': self.placeholder,
            'sort_order': self.sort_order,
            'is_active': self.is_active,
            'field_category': self.field_category,
            'is_visible': self.is_visible,
            'system_required': self.system_required,
            'description': self.description,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }
    
    def __repr__(self):
        return f'<WorkOrderField {self.name}>'


class WorkOrderFieldValue(db.Model):
    """工单自定义字段值"""
    __tablename__ = 'work_order_field_values'
    
    id = db.Column(db.Integer, primary_key=True)
    work_order_id = db.Column(db.Integer, db.ForeignKey('work_orders.id'), nullable=False)
    field_id = db.Column(db.Integer, db.ForeignKey('work_order_fields.id'), nullable=False)
    value = db.Column(db.Text)
    
    field = db.relationship('WorkOrderField', backref='field_values')
    
    __table_args__ = (db.UniqueConstraint('work_order_id', 'field_id'),)
    
    def __repr__(self):
        return f'<WorkOrderFieldValue {self.field.name}={self.value}>'
